import * as utils from '../utils'

function createCourse10 (gl: WebGLRenderingContext) {
  gl.clearColor(0.0, 0.0, 0.0, 1.0)
  gl.clear(gl.COLOR_BUFFER_BIT)
  const vectexShaderSrc = `
    attribute vec4 a_Position;
    uniform mat4 u_Matrix;
      void main() {
        gl_Position = u_Matrix * a_Position;
      }
    `

  const fragmentShaderSrc = `
    precision mediump float;
    uniform vec4 u_FragColor;
      void main() {
          gl_FragColor = u_FragColor;
      }
    `
  const program = utils.initShaders(gl, vectexShaderSrc, fragmentShaderSrc)

  function initVertexBuffers () {
    // 将attribute变量跟javascript变量绑定在一起
    const aPosition = gl.getAttribLocation(program, 'a_Position')
    const uMatrix = gl.getUniformLocation(program, 'u_Matrix')

    const angle = 45 / 180 * Math.PI
    const sin = Math.sin(angle)
    const cos = Math.cos(angle)

    // webgl中是主列的矩阵
    /*
    *  原先的矩阵旋转角度a，平移bx, by
        cosa -sina 0 bx          x
        sina  cosa 0 by          y
        0     0    1 0           z
        0     0    0 1           1
    */
    const matrix = new Float32Array([
      cos, sin, 0.0, 0.0,
      -sin, cos, 0.0, 0.0,
      0.0, 0.0, 1.0, 0.0,
      0.2, 0.3, 0.0, 1.0
    ])
    gl.uniformMatrix4fv(uMatrix, false, matrix)

    const uFragColor = gl.getUniformLocation(program, 'u_FragColor')
    gl.uniform4f(uFragColor, 1.0, 0.0, 0.0, 1.0)
    const vertices = new Float32Array([
      0.0, 0.5, -0.5, -0.5, 0.5, -0.5
    ])
    // 创建缓冲区对象
    const vertexBuffer = gl.createBuffer()
    // 绑定缓冲区
    gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer)
    // 向缓冲区写入对象
    gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW)
    // 将缓冲区对象分配个attribute变量
    gl.vertexAttribPointer(aPosition, 2, gl.FLOAT, false, 0, 0)
    // 开启attribute变量
    gl.enableVertexAttribArray(aPosition)

    return 3
  }

  const count = initVertexBuffers()

  gl.drawArrays(gl.TRIANGLES, 0, count)
}

export {
  createCourse10
}
